package top.easyblog.core.mq.consumer;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import top.easyblog.core.mq.bean.MappingVisitMessage;
import top.easyblog.core.mq.bean.UrlMappingMessage;
import top.easyblog.core.service.MappingVisitRecordService;
import top.easyblog.core.support.lock.RedisDistributeLockFactory;
import top.easyblog.core.util.JsonUtils;

import java.util.Optional;

/**
 * 短链访问事件消息消费者
 *
 * @author: frank.huang
 * @date: 2023-12-29 23:29
 */
@Slf4j
@Component
public class MappingVisitMessageConsumer extends AbstractRedisMessageConsumer<MappingVisitMessage> {

    @Getter
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Getter
    @Autowired
    private RedisDistributeLockFactory redisDistributeLockFactory;

    @Autowired
    private MappingVisitRecordService mappingVisitRecordService;

    @Getter
    @Value("${redis.mq.consumer.url-mapping-visit.enable:true}")
    private boolean enabled;

    @Getter
    @Value("${redis.mq.consumer.url-mapping-visit.topic}")
    private String topic;


    @Override
    public MappingVisitMessage deserialize(Message message) {
        RedisSerializer<?> valueSerializer = redisTemplate.getValueSerializer();
        return Optional.ofNullable(message).map(Message::getBody)
                .map(msg -> {
                    String deserialize = (String) valueSerializer.deserialize(msg);
                    return JsonUtils.parseObject(deserialize, MappingVisitMessage.class);
                }).orElse(null);
    }

    @Override
    public void doTask(MappingVisitMessage message) {
        mappingVisitRecordService.saveMappingVisitRecord(message);
    }


}
